#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/2/5 16:20
# @Author  : Fancy
# @FileName: reports.py
# @Software: PyCharm
# @runstate    ：
# utils/reports.py
from pathlib import Path
import json
import csv

class ReportGenerator:
    def __init__(self, output_dir: str = 'reports'):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)

    def save_json(self, data: dict, filename: str) -> str:
        path = self.output_dir / f"{filename}.json"
        path.write_text(json.dumps(data, indent=2))
        return str(path)

    def save_csv(self, data: list, filename: str) -> str:
        path = self.output_dir / f"{filename}.csv"
        if not data:
            print (f"警告：数据为空，未生成 {filename}.csv")
            return ""


        with open (path, 'w', newline='', encoding='utf-8') as file:
            # 定义字段名（表头）
            fieldnames = ["Table Name", "Missing in Target", "Missing in Source", "Type Mismatch", "Missing in Count"]
            writer = csv.DictWriter (file, fieldnames=fieldnames)

            # 写入表头
            writer.writeheader ()
            # 写入每张表的数据
            for table, diff in data.items ():
                missing_in_target = ", ".join ([str (field) for field in diff['missing_in_target']]) if diff[
                    'missing_in_target'] else "None"
                missing_in_source = ", ".join ([str (field) for field in diff['missing_in_source']]) if diff[
                    'missing_in_source'] else "None"
                type_mismatch = ", ".join (
                    [f"{col}: {src_type} -> {tgt_type}" for col, src_type, tgt_type in diff['type_mismatch']]) if diff[
                    'type_mismatch'] else "None"
                missing_source_count = diff.get('missing_source_count', [])
                if missing_source_count:
                    # 这里假设 missing_source_count 是一个列表，里面存储了表名、源记录数和目标记录数
                    missing_source_count_str = ", ".join (
                        [f"{table}: {src} (Source), {tgt} (Target)" for table, src, tgt in missing_source_count])
                else:
                    missing_source_count_str = "0"  # 如果没有差异，则输出0

                # 写入一行数据
                writer.writerow ({
                    "Table Name": table,
                    "Missing in Target": missing_in_target,
                    "Missing in Source": missing_in_source,
                    "Type Mismatch": type_mismatch,
                    "Missing in Count": missing_source_count_str
                })
        return str (path)


